---
author: Marcus Rohrmoser
categories:
- en
- development
date: "2013-12-05T14:37:10+00:00"
tags:
- Catch
- Cocoa
- Exception
- iOS
- JavaScript
- NSError
- Objective C
- stringByEvaluatingJavaScriptFromString
- Throw
- UIWebView
title: Catch JavaScript exceptions in UIWebViews
type: post
url: /2013/12/catch-javascript-exceptions-in-uiwebviewstringbyevaluatingjavascriptfromstring/
yourls_shorturl:
- http://mro.name/4j
---
A small but useful category method on [UIWebView][1]: Turn uncaught JavaScript Exception into a [NSError][2]!

<pre class="line-numbers"><code class="language-objc">
//
// Created by Marcus Rohrmoser on 05.12.13.
// Copyright (c) 2013 Marcus Rohrmoser mobile Software. All rights reserved.
//

#import "UIWebView+JavaScriptNSError.h"

#define NSERROR_UIWEBVIEW_SCRIPT @"NSERROR_UIWEBVIEW_SCRIPT"
#define NSERROR_UIWEBVIEW_SCRIPT_CODE 1

@implementation UIWebView(JavaScriptNSError)

-(NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script error:(NSError * __autoreleasing *)error
{
  NSString *errorPrefix = NSERROR_UIWEBVIEW_SCRIPT;
  NSString *exec = [NSString stringWithFormat:@"try { %@ } catch (e) { '%@' + e; }", script, errorPrefix, nil];
  NSString *ret = [self stringByEvaluatingJavaScriptFromString:exec];

  if( ![ret hasPrefix:errorPrefix] )
    return ret;

  if( error ) {
    NSString *msg = [ret substringFromIndex:errorPrefix.length];
    NSDictionary *ui = @ {
      NSLocalizedDescriptionKey: msg,
      NSFilePathErrorKey:[self.request.URL absoluteString],
      NSURLErrorKey: self.request.URL,
      NSLocalizedFailureReasonErrorKey: msg,
      NSURLErrorFailingURLErrorKey: self.request.URL,
      NSURLErrorFailingURLStringErrorKey: self.request.URL
    };
    *error = [NSError errorWithDomain:NSERROR_UIWEBVIEW_SCRIPT code:NSERROR_UIWEBVIEW_SCRIPT_CODE userInfo:ui];
  }
  return nil;
}
@end
</code></pre>

 [1]: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebView_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006950-CH3-SW21
 [2]: https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html